본문으로 건너뛰기

3.1Readme.md ~ 3.5Readme

Partial, Required , Readonly, Pick, Record

Partial

  • 기존의 객체의 속성을 전부 옵셔널로 만드는 Partial함수이다.
type Mypartial<T> = {
[p in keyof T]?: T[P];
};

type Result = Mypartial<{ a: string; b: number }>;
  • Required는 모든 속성을 옵셔널이 아니게 만들 수 있다.
  • 모든 속성을 readonly가 되게 만들 수 있음
type MyRequired<T> = {
[P in keyof T]-?: T[P];
};

type Result = MyQequired<{ a?: string; b?: number }>;

-a| c |d 처럼 d 처럼 객체의 속성이 아닌 경우는 무시하고 나머지 a|c속성만 추리도록할 수 있다.

type MyPick<T,K> ={
[p in (K extends Keyof T ? K : never)] : T[P];
}
type Result = Mypick<{a : string, b: number, c:number}, >

Exclude, Extract, Omit, NonNullable

type MyExclude<T, U> = T extends U ? Never : T;
type Result = MyExclude<1 | "2" | 3, string>;
  • 1 | "2" | 3은 유니언이므로 분배법칙이 실행된다.
  • 이를 이용해 지정한 타입만 추출해낼 수 있다.

Omit

  • Omit은 지정한 속성을 제거하는 타입이다.
type MyOmit<T, k extends keyof any> = Pick<T, Exclude<keyof T, K>>;

type Result = MyOmit<{ a: "1"; b: 2; c: true }, "a" | "c">;
  • Omit 타입은 pick 타입과 반대되는 행동을 한다. Omit 타입은 PickExclude 타입을 활용한다.
  • 타입에서 nullundefined을 제거하는 NouNullable타입을 만들 수 있다.
type MyNonNullable<T> = T extends null | undefined ? never : T;
type Result = MyNonNullable<string | number | null | undefined>;

Parameters, ConstructorParameters, ReturnType, InstanceType

type MyParameters<T extends (...args: any) => any> = T extends (
...args: infer P
) => any
? P
: never;

type MyConstructorParameters<T extends abstract new (...args : any)=>any>